package com.yingpai.fitness.dvp_2_0.main.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.ActivityManager;
import com.yingpai.fitness.dvp_2_0.common.util.ContextUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.wx.WxBindBean;
import com.yingpai.fitness.entity.wx.WxIsExistBean;
import com.yingpai.fitness.entity.wx.WxVerificaPhoneBean;
import com.yingpai.fitness.dvp_2_0.main.util.XCountDownTimer;
import com.yingpai.fitness.dvp_2_0.main.util.NetWorkUtil;
import com.yingpai.fitness.dvp_2_0.main.util.encrypt.RsaEncrypt;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * 微信绑定手机号
 * Created by ASUS on 2018/10/25.
 */

public class WeChatBindPhoneActivity extends CommonActivity {

    @BindView(R.id.registerPhoneEt)
    EditText registerPhoneEt;
    @BindView(R.id.point)
    TextView mPointText;
    @BindView(R.id.registerPasswordEt)
    EditText registerPasswordEt;
    @BindView(R.id.register_verification_code_et)
    EditText registerVerificationCodeEt;
    @BindView(R.id.registerVercodeTv)
    TextView registerVercodeTv;
    @BindView(R.id.registerInviteEt)
    EditText registerInviteEt;
    @BindView(R.id.yaoqingma_layout)
    RelativeLayout yaoqingma_layout;
    //0需要绑定，1无需绑定
    private int flag = 0;
    private String phone;
    private String infoUserWxId = "";
    // 获取加密类
    private RsaEncrypt rsaEncryptor = null;
    private XCountDownTimer timer;//倒计时


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_wechat_bind_phone);

    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            infoUserWxId = bundle.getString("infoUserWxId");
        }

        rsaEncryptor = RsaEncrypt.getInstance(ContextUtil.getContext());

        registerPhoneEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mRunnable != null) {
                    mHandler.removeCallbacks(mRunnable);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                phone = s.toString().trim();
                // 输入了手机号
                // 并且手机号是11位
                if (!TextUtils.isEmpty(phone) && phone.length() == 11) {
                    mHandler.postDelayed(mRunnable, 1000);
                }

            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    @OnClick({R.id.registerVercodeTv, R.id.goRegisterBtn, R.id.protocol, R.id.registerbackIv})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.registerVercodeTv:
                //先获取到填写的手机号
                if (TextUtils.isEmpty(phone)) {
                    //电话号是空的，吐司提示
                    showToast("请填写手机号");
                    registerPhoneEt.requestFocus();
                } else if (phone.length() != 11) {
                    showToast("请填写正确的手机号");
                } else if (NetWorkUtil.isConnected() && NetWorkUtil.isAvailableByPing()) {
                    getRegisterVercode(phone);
                } else {
                    showToast("网络不可用，请检查网络设置");
                }
                break;
            case R.id.goRegisterBtn:
                String password = registerPasswordEt.getText().toString();
                String vilidateCode = registerVerificationCodeEt.getText().toString();
                String inviteCode = registerInviteEt.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    showToast("请输入手机号");
                } else if (flag == 0 && TextUtils.isEmpty(password)) {
                    showToast("请输入密码");
                } else if (TextUtils.isEmpty(vilidateCode)) {
                    showToast("请输入验证码");
                } else {
                    try {
                        showDialog(this,"绑定中...");
                        HttpParams httpParams = new HttpParams();
                        httpParams.put("phoneNo", rsaEncryptor.encryptWithBase64(phone));
                        httpParams.put("password", rsaEncryptor.encryptWithBase64(password));
                        httpParams.put("infoUserWxId",infoUserWxId);
                        httpParams.put("inviteCode", inviteCode);
                        httpParams.put("vilidateCode",vilidateCode);
                        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.BIND_PHONENO, httpParams, Url.BIND_PHONENO, new Callback<WxBindBean>() {
                            @Override
                            public void onSuccess(WxBindBean bean) {
                                dismissDialog();
                                if (bean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                    bean.getData().getData().setRegisterId(JPushInterface.getRegistrationID(context));
                                    SharedPreferencesHelp.putBean(Constant.TOKENBEAN, bean.getData().getData());
                                    JPushInterface.setAlias(context,bean.getData().getData().getId(),"妖动动" + bean.getData().getData().getId());
                                    ActivityManager.getActivityManager().popAllActivity();
                                    startFinishActivity(HomeActivity.class);

                                } else {
                                    showToast(bean.getMessage());
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.protocol:
                startActivity(ProtocolActivity.class);
                break;
            case R.id.registerbackIv:
                finishActivity();
                break;
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (Constant.EDIT_OK == msg.what) {//输入完成
                //showToast("输入完成");
                HttpParams httpParams = new HttpParams();
                httpParams.put("phoneNo", phone);
                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.CHECK_PHONENO, httpParams, Url.CHECK_PHONENO, new com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback<WxIsExistBean>() {
                    @Override
                    public void onSuccess(WxIsExistBean bean) {
                        if (bean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                            if (bean.getData().getSuccess().equals(Constant.REQUEST_FAIL)) {//用户没有绑定，需要绑定
                                mPointText.setVisibility(View.GONE);//
                                flag = 0;
                                yaoqingma_layout.setVisibility(View.VISIBLE);
                                registerPasswordEt.setVisibility(View.VISIBLE);
                            } else if (bean.getData().getSuccess().equals(Constant.REQUEST_SUCCESS)) {//用户已经绑定，无需绑定
                                mPointText.setVisibility(View.VISIBLE);
                                flag = 1;
                                yaoqingma_layout.setVisibility(View.GONE);
                                registerPasswordEt.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
            }
        }
    };

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(Constant.EDIT_OK);
        }
    };

    private void getRegisterVercode(String phone) {
        showDialog(this,"获取中...");
        String phoneNumBase64 = null;
        try {
            phoneNumBase64 = rsaEncryptor.encryptWithBase64(phone);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpParams httpParams = new HttpParams();
        httpParams.put("phoneNo", phoneNumBase64);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_VALIDATE_CODE, httpParams, Url.GET_VALIDATE_CODE, new Callback<WxVerificaPhoneBean>() {
            @Override
            public void onSuccess(WxVerificaPhoneBean bean) {
                dismissDialog();
                if (bean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                    timer = new XCountDownTimer(60 * 1000, 1000,
                            registerVercodeTv, 1);
                    timer.start();
                    showToast(bean.getData().getMessage());
                } else {
                    showToast(bean.getMessage());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
                //showToast("发送超时");
            }
        });
    }
}
